package aszm.chahaospider.utils;

import java.io.InputStream;
import java.sql.SQLException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import aszm.chahaospider.constants.Constants;

public class MybatisUtils {
	private static final Logger Log = Logger.getLogger(MybatisUtils.class.getName());

	public enum CRUD_Enum {
		Add, Delete, Update, Query, List

	}

	/*
	 * 获取数据库访问链接
	 */
	public static SqlSession getSqlSession() {
		SqlSession session = null;
		try {
			InputStream stream = Resources.getResourceAsStream(Constants.CONFIG_PATH);
			// 可以根据配置的相应环境读取相应的数据库环境
			// SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(
			// stream, "development");
			SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
			session = factory.openSession();
		} catch (Exception e) {
			Log.error(e);
		}
		return session;
	}

	/*
	 * 获取数据库访问链接
	 */
	public static void closeSession(SqlSession session) {
		session.commit();
		session.close();
	}

	/*
	 * 返回操作记录消息
	 */
	public static void showMessages(CRUD_Enum type, int count) {
		switch (type) {
		case Add:
			Log.info("添加了" + count + "条记录。");
			break;
		case Delete:
			Log.info("删除了" + count + "条记录。");
			break;
		case Update:
			Log.info("更新了" + count + "条记录。");
			break;
		case Query:
			Log.info("匹配了" + count + "条记录。");
			break;
		case List:
			Log.info("共有" + count + "条记录。");
			break;
		default:
			break;
		}
	}
}
